package com.h2cloud.excel;

/**
 * @Package: com.h2cloud.excel
 * @ClassName: ExcelHeaderMerger
 * @Author: wulongkai
 * @CreateTime: 2023/8/7 14:52
 * @Description:
 */

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelHeaderMerger extends AnalysisEventListener<Map<Integer, String>> {
    private List<Map<Integer, String>> mergedHeaders = new ArrayList<>();
    private Map<String, Integer> headerCountMap = new HashMap<>();

    @Override
    public void invoke(Map<Integer, String> rowData, AnalysisContext context) {
        List<String> mergedHeader = new ArrayList<>();
        for (Map.Entry<Integer, String> entry : rowData.entrySet()) {
            String cellValue = entry.getValue();
            int count = headerCountMap.getOrDefault(cellValue, 0);
            headerCountMap.put(cellValue, count + 1);
            String mergedCellValue = cellValue;
            if (count > 0) {
                mergedCellValue = cellValue + " (" + count + ")";
            }
            mergedHeader.add(mergedCellValue);
        }
        mergedHeaders.add(rowData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 数据读取完成后的逻辑处理
        writeMergedHeadersToExcel();
    }

    public void writeMergedHeadersToExcel() {
        String outputFilePath = "/Users/a58/Downloads/file.xlsx";
        File file = new File(outputFilePath);
        if (!file.exists()) {//如果文件不存在
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        ExcelWriter excelWriter = EasyExcel.write(outputFilePath).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0).build();

        // 写入合并后的表头数据
        for (Map<Integer, String> rowData : mergedHeaders) {
            List<String> rowValues = new ArrayList<>();
            for (Map.Entry<Integer, String> entry : rowData.entrySet()) {
                rowValues.add(entry.getValue());
            }
            excelWriter.write(rowValues, writeSheet);
        }

        // 写入完成后关闭 ExcelWriter
        excelWriter.finish();
    }
}
